package com.ruoyi.pos.api.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtil;
import com.ruoyi.common.utils.SaltUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.json.JsonUtils;
import com.ruoyi.common.utils.qugongbao.QugongbaoUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pos.api.dto.common.ExchangeDto;
import com.ruoyi.pos.api.dto.common.MemberRegDto;
import com.ruoyi.pos.api.dto.user.*;
import com.ruoyi.pos.api.service.common.ICommonService;
import com.ruoyi.pos.api.service.user.IUserManageService;
import com.ruoyi.pos.api.utils.CommonUtils;
import com.ruoyi.pos.api.vo.user.*;
import com.ruoyi.pos.web.domain.*;
import com.ruoyi.pos.web.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luobo
 * @title: UserManageServiceImpl
 * @projectName pos
 * @description: TODO
 * @date 2021-11-08 09:42:32
 */
@Service
public class UserManageServiceImpl implements IUserManageService {
    private static final Logger log = LoggerFactory.getLogger(UserManageServiceImpl.class);

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CommonUtils commonUtils;

    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TUserTeamInfoMapper userTeamInfoMapper;
    @Autowired
    private TNoticeInfoMapper noticeInfoMapper;
    @Autowired
    private TOpinionInfoMapper opinionInfoMapper;
    @Autowired
    private TOpinionImgInfoMapper opinionImgInfoMapper;
    @Autowired
    private TUserNoticeInfoMapper userNoticeInfoMapper;
    @Autowired
    private TUserAddressInfoMapper userAddressInfoMapper;
    @Autowired
    private TTerminalTransInfoMapper terminalTransInfoMapper;
    @Autowired
    private TTerminalInfoMapper terminalInfoMapper;
    @Autowired
    private TGoldAwardSerialInfoMapper tGoldAwardSerialInfoMapper;
    @Autowired
    private TGoldDealSerialInfoMapper tGoldDealSerialInfoMapper;
    @Autowired
    private TStatisticInfoMapper tStatisticInfoMapper;
    @Autowired
    private TRebateSetInfoMapper tRebateSetInfoMapper;
    @Autowired
    private TGoldAwardSerialInfoMapper goldAwardSerialInfoMapper;
    @Autowired
    private TGoldDealSerialInfoMapper goldDealSerialInfoMapper;
    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    @Autowired
    private TTerminalGoodsInfoMapper terminalGoodsInfoMapper;
    @Autowired
    private TTerminalTransFlowInfoMapper terminalTransFlowInfoMapper;
    @Autowired
    private TUserDefaultInfoMapper userDefaultInfoMapper;
    @Autowired
    private TGradeInfoMapper tGradeInfoMapper;

    @Autowired
    private ICommonService commonService;
    @Autowired
    private Environment env;
    @Autowired
    QugongbaoUtils qugongbaoUtils;

    //查询用户信息
    @Override
    @Transactional
    public UserInfoVo queryTUserInfoVo() throws Exception {
        String userId = commonUtils.getUserId();
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(userId);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(user, vo);
        if (StringUtils.isNotEmpty(user.getSuperiorUserId())) {
            TUserInfo supUser = userInfoMapper.selectTUserInfoByUserId(user.getSuperiorUserId());
            vo.setMyServiceProviderName(supUser.getUserName());
            vo.setMyServiceProviderPhone(supUser.getUserPhone());
        }
        TGradeInfo grade = tGradeInfoMapper.selectTGradeInfoById(user.getGradeId());
        vo.setGradeCode(grade.getGradeCode());
        vo.setGradeName(grade.getGradeName());

        DataStatisticsDto dto = new DataStatisticsDto();
        dto.setUserId(userId);
        DataStatisticsVo statisticsVo = tStatisticInfoMapper.queryTStatisticSum(dto);
        vo.setMyTransMoney(statisticsVo == null ? BigDecimal.ZERO : statisticsVo.getMyTransMoney());//我的交易金额
        vo.setMyTerminalNum(statisticsVo == null ? BigDecimal.ZERO : statisticsVo.getMyTerminalNum());//我的终端数
        transUserInfoVo(vo);
        return vo;
    }

    //翻译用户信息
    public UserInfoVo transUserInfoVo(UserInfoVo vo){
        vo.setAuditStatusShow(AuditStatusEnum.getEnumsByCode(vo.getUserStatus()).getValue());
        vo.setUserStatusShow("");
        if (StringUtils.isNotEmpty(vo.getSuperiorUserId())) {
            TUserInfo supUser = userInfoMapper.selectTUserInfoByUserId(vo.getSuperiorUserId());
            vo.setSuperiorUserName(supUser.getUserName());
        }
        vo.setBalance(vo.getBalanceSum().subtract(vo.getBalanceUse()).subtract(vo.getBalanceWithdraw()));//用户当前可提现金额
        return vo;
    }


    //保存用户信息或【支付密码设置】
    @Override
    @Transactional
    public void saveUserInfo(UserDto userDto) throws Exception {
//        String userId = commonUtils.getUserId();
        TUserInfo user = userInfoMapper.selectUserByUserPhone(userDto.getUserPhone());
        if (StringUtils.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        BeanUtils.copyProperties(userDto, user);
        String redisCode = redisCache.getVerifyCode(user.getUserPhone());
        if (StringUtils.isNull(redisCode)) {
            throw new RuntimeException("验证码过期");
        }
        /*if (!redisCode.equals(userDto.getVerifyCode())) {
            throw new RuntimeException("验证码错误");
        }*/
        if (StringUtils.isNotEmpty(userDto.getPayPassword()) && StringUtils.isNotEmpty(userDto.getUserPhone())) {//支付密码不为空
            Map<String, String> map = editPassword(userDto.getPayPassword());
            user.setPaySalt(map.get("salt"));//支付盐
            user.setPayPassword(map.get("password"));//支付密码
        } else {//实名认证
            checkRequired(userDto);
            user.setAutonymType(YesOrNoEnums.YES.getCode());//1：未认证 0：认证
            user.setAutonymTime(DateUtils.getNowDate());
            user.setAuditStatus(AuditStatusEnum.PASS_AUDIT.getCode());
        }
        if (StringUtils.isNotEmpty(userDto.getPassword()) && StringUtils.isNotEmpty(userDto.getUserPhone())) {//登录密码修改
            Map<String, String> map = editPassword(userDto.getPassword());
            user.setSalt(map.get("salt"));//登录盐
            user.setPassword(map.get("password"));//登录密码
        }
        TUserInfo mapper = new TUserInfo();
        mapper.setSuperiorUserId(user.getUserId());
        List<TUserInfo> supUsers = userInfoMapper.selectTUserInfoList(mapper);
        supUsers.stream().forEach(supUser -> {
            supUser.setSupUserPhone(user.getUserPhone());
            supUser.setSuperiorUserName(user.getUserName());
            userInfoMapper.updateTUserInfo(supUser);
        });
        userInfoMapper.updateTUserInfo(user);
    }

    public void checkRequired(UserDto userDto) {
        if (StringUtils.isEmpty(userDto.getUserName())) {
            throw new RuntimeException("请填写用户真实姓名");
        }
        if (StringUtils.isEmpty(userDto.getIdentityMark())) {
            throw new RuntimeException("请填写用户真实身份证号");
        }
        if (StringUtils.isEmpty(userDto.getBankCardMark())) {
            throw new RuntimeException("请填写用户真实银行卡号");
        }
    }

    public Map<String,String> editPassword(String pass){
        Map<String,String> map = new HashMap<>();
        String salt = SaltUtils.createSalt();
        String password = SaltUtils.salt(pass, salt);
        map.put("salt",salt);//盐
        map.put("password",password);//密码
        return map;
    }

    //保存收货地址信息//修改
    @Override
    @Transactional
    public void saveUserAddressInfo(UserAddressDto userAddressDto) throws Exception {
        String userId = commonUtils.getUserId();
        TUserAddressInfo userAddr = new TUserAddressInfo();
        BeanUtils.copyProperties(userAddressDto,userAddr);
        if (StringUtils.isNotEmpty(userAddressDto.getId())){//id不等于null 这是修改
            if (YesOrNoEnums.NO.getCode().equals(userAddressDto.getIsValid())){//修改
                queryDeitaddr(userId,userAddressDto.getId());
            }
            userAddressInfoMapper.updateTUserAddressInfo(userAddr);
        }else {//添加
            userAddr.setUserId(userId);
            userAddr.setId(IdUtils.simpleUUID());
            userAddr.setCreateTime(DateUtils.getNowDate());
            if (YesOrNoEnums.NO.getCode().equals(userAddressDto.getIsValid())){//是否查询默认地址（1：是，0：否）NO:0 YES:1
                queryDeitaddr(userId,"");
            }
            userAddressInfoMapper.insertTUserAddressInfo(userAddr);
        }
    }

    public void queryDeitaddr(String userId,String id){
        TUserAddressInfo userAddr = new TUserAddressInfo();
        //修改上一个默认地址，状态改为1
        userAddr.setUserId(userId);
        userAddr.setIsValid(YesOrNoEnums.NO.getCode());//是否查询默认地址（1：是，0：否） NO:0 YES:1
        //先查询后修改
        List<TUserAddressInfo> addressInfos = userAddressInfoMapper.selectTUserAddressInfoList(userAddr);
        if (addressInfos.size() > 0 && !id.equals(addressInfos.get(0).getId())){
            userAddr.setIsValid(YesOrNoEnums.YES.getCode());//是否查询默认地址（1：是，0：否） NO:0 YES:1
            userAddr.setId(addressInfos.get(0).getId());
            userAddressInfoMapper.updateTUserAddressInfo(userAddr);
        }
    }

    //查询收货地址列表
    @Override
    public Map<String, Object> queryUserAddressList(UserAddressDto userAddressDto) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String userId = commonUtils.getUserId();
        if (StringUtils.isNotEmpty(userAddressDto.getId())) {//id查询 回填
            TUserAddressInfo tUserAddressInfo = userAddressInfoMapper.selectTUserAddressInfoById(userAddressDto.getId());
            UserAddressVo vo = new UserAddressVo();
            BeanUtils.copyProperties(tUserAddressInfo, vo);
            resultMap.put("list", vo);
        } else {
            TUserAddressInfo mapper = new TUserAddressInfo();
            mapper.setUserId(userId);
            mapper.setIsValid(userAddressDto.getIsValid());
            PageUtil.startPage(userAddressDto);
            List<TUserAddressInfo> list = userAddressInfoMapper.selectTUserAddressInfoList(mapper);
            List<UserAddressVo> voList = new ArrayList<UserAddressVo>();
            resultMap.put("total", 0L);
            Optional.ofNullable(list).ifPresent(lists -> {
                resultMap.put("total", new PageInfo(lists).getTotal());
                lists.stream().forEach(bean -> {
                    UserAddressVo vo = new UserAddressVo();
                    BeanUtils.copyProperties(bean, vo);
                    voList.add(vo);
                });
            });
            resultMap.put("lists", voList);
        }
        return resultMap;
    }

    //查询平台公告列表
    @Override
    public List<UserNoticeVo> queryUserNoticeList(UserNoticeDto userNoticeDto) throws Exception {
        String userId = commonUtils.getUserId();
        TUserInfo userInfo = new TUserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserNoticeType(YesOrNoEnums.YES.getCode());
        userInfoMapper.updateTUserInfo(userInfo);
        TUserNoticeInfo mapper = new TUserNoticeInfo();
        mapper.setIsValid(YesOrNoEnums.YES.getCode());
        mapper.setUserId(userId);
        PageUtil.startPage(userNoticeDto);
        List<UserNoticeVo> list = userNoticeInfoMapper.selectTUserNoticeList(mapper);
        return list;
    }

    //查询平台公告详情
    @Override
    @Transactional
    public UserNoticeVo queryUserNoticeDetail(UserNoticeDto userNoticeDto) throws Exception {
        TUserNoticeInfo mapper = new TUserNoticeInfo();
        mapper.setUserId(commonUtils.getUserId());
        mapper.setNoticeId(userNoticeDto.getNoticeId());
        List<TUserNoticeInfo> infoList = userNoticeInfoMapper.selectTUserNoticeInfoList(mapper);
        if (null == infoList || infoList.size() == 0) {
            TUserNoticeInfo userNotice = new TUserNoticeInfo();
            userNotice.setId(IdUtils.simpleUUID());
            userNotice.setIsRead(YesOrNoEnums.YES.getCode());
            userNotice.setUserId(commonUtils.getUserId());
            userNotice.setNoticeId(userNoticeDto.getNoticeId());
            userNotice.setReadTime(DateUtils.getNowDate());
            userNotice.setCreateTime(DateUtils.getNowDate());
            userNoticeInfoMapper.insertTUserNoticeInfo(userNotice); //标记为已读
        }
        TNoticeInfo notice = noticeInfoMapper.selectTNoticeInfoById(userNoticeDto.getNoticeId());
        UserNoticeVo vo = new UserNoticeVo();
        BeanUtils.copyProperties(notice, vo);
        return vo;
    }


    //发布意见
    @Override
    @Transactional
    public void saveUserOpinionInfo(UserOpinionDto userOpinionDto) throws Exception {
        String userId = commonUtils.getUserId();
        TOpinionInfo info = new TOpinionInfo();
        info.setId(IdUtils.simpleUUID());
        info.setContactWay(userOpinionDto.getContactWay());
        info.setUserId(userId);
        info.setOpinion(userOpinionDto.getOpinion());
        info.setCreateTime(DateUtils.getNowDate());
        info.setReplyState(YesOrNoEnums.NO.getCode());
        opinionInfoMapper.insertTOpinionInfo(info);
        if (StringUtils.isNotEmpty(userOpinionDto.getOpinionImg())) {
            for (String opImg : userOpinionDto.getOpinionImg().split(",")) {
                TOpinionImgInfo img = new TOpinionImgInfo();
                img.setOpinionId(info.getId());
                img.setId(IdUtils.simpleUUID());
                img.setOpinionImg(opImg);
                opinionImgInfoMapper.insertTOpinionImgInfo(img);
            }
        }
    }

    //查询意见列表
    @Override
    public List<UserOpinionVo> queryUserOpinionList(UserOpinionDto userOpinionDto) throws Exception {
        String userId = commonUtils.getUserId();
        TOpinionInfo mapper = new TOpinionInfo();
        mapper.setUserId(userId);
        List<UserOpinionVo> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(userOpinionDto.getId())) {
            TOpinionInfo op = opinionInfoMapper.selectTOpinionInfoById(userOpinionDto.getId());
            UserOpinionVo vo = new UserOpinionVo();
            BeanUtils.copyProperties(op, vo);
            list.add(vo);
        } else {
            PageUtil.startPage(userOpinionDto);
            list = opinionInfoMapper.selectTOpinionInfoListForVo(mapper);
        }
        list.stream().forEach(bean -> {
            TOpinionImgInfo imgMapper = new TOpinionImgInfo();
            imgMapper.setOpinionId(bean.getId());
            List<TOpinionImgInfo> imgList = opinionImgInfoMapper.selectTOpinionImgInfoList(imgMapper);
            List<UserOpinionVo.OpinionImgBean> imgBeanList = new ArrayList<UserOpinionVo.OpinionImgBean>();
            Optional.ofNullable(imgList).ifPresent(list1 -> {
                list1.stream().forEach(img -> {
                    UserOpinionVo.OpinionImgBean imgBean = new UserOpinionVo.OpinionImgBean();
                    BeanUtils.copyProperties(img, imgBean);
                    imgBeanList.add(imgBean);
                });
            });
            bean.setImgList(imgBeanList);
        });
        return list;
    }

    //查询用户团队列表
    @Override
    public UserTeamVo queryTeamUserList(UserTeamDto userTeamDto) throws Exception {
        String userId = commonUtils.getUserId();
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(userId);
        UserTeamVo vo = new UserTeamVo();
        if (StringUtils.isNotEmpty(user.getInviteCode())) {
            TUserInfo userParent = userInfoMapper.selectTUserInfoByUserId(user.getSuperiorUserId());
            if (null != userParent) {
                vo.setParentUserName(userParent.getUserName());
                vo.setParentUserImg(userParent.getUserImg());
                vo.setParentUserPhone(userParent.getUserPhone());
            }
        }
        PageUtil.startPage(userTeamDto);
        userTeamDto.setUserId(userId);
        List<UserTeamListVo> list = userTeamInfoMapper.selectUserTeamList(userTeamDto);
        List<UserTeamListVo> resultList = list;
        if ("1".equals(userTeamDto.getIsContainOwn())) { //查询不包含自己的团队列表
            resultList = list.stream()
                    .filter(bean ->!userId.equals(bean.getUserId()))
                    .collect(Collectors.toList());
        }
        vo.setTotal(0L);
        if (null != resultList) {
            vo.setTotal(new PageInfo<>(resultList).getTotal());
            Optional.ofNullable(resultList).ifPresent(lists->{
                lists.stream().forEach(bean->{
                    if (StringUtils.isNull(bean.getBalanceSum())){
                        bean.setBalanceSum(BigDecimal.ZERO);
                    }
                });
            });
        }
        vo.setTeamList(resultList);
        return vo;
    }

    //查询兑换记录列表
    @Override
    public List<ExchangeOrderVo> queryExchangeRecordList(OrderDto orderDto) throws Exception {
        String userId = commonUtils.getUserId();
        orderDto.setUserId(userId);
        PageUtil.startPage(orderDto);
        List<ExchangeOrderVo> orderList = orderInfoMapper.queryExchangeRecordList(orderDto);
        TTerminalGoodsInfo terminalGoodsInfo = new TTerminalGoodsInfo();
        terminalGoodsInfo.setIsValid(YesOrNoEnums.YES.getCode());
        List<TTerminalGoodsInfo> goodsInfos = terminalGoodsInfoMapper.selectTTerminalGoodsInfoList(terminalGoodsInfo);
        orderList.stream().forEach(order ->{
            for (TTerminalGoodsInfo info : goodsInfos) {
                if (order.getGoodsId().equals(info.getId())) {
                    order.setOrderTypeShow(Optional.ofNullable(OrderTypeEnum.getEnumsByCode(order.getOrderType())).map(item -> item.getValue()).orElse(order.getOrderType()));
                    order.setOrderStatusShow(Optional.ofNullable(OrderStatusEnums.getEnumsByCode(order.getOrderStatus())).map(item -> item.getValue()).orElse(order.getOrderStatus()));
                    order.setGoodsName(info.getGoodsName());
                }
            }
        });
        return orderList;
    }

    //查询交易金/奖励金序列号列表
    @Override
    public Map<String, Object> queryGoldSerialNumberList(ExchangeDto exchangeDto) throws Exception {
        //(1:交易金序列,2:号奖励金序列号)必填
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("notTotal", 0L);//查询所有的序列号的中条数
        resultMap.put("yesTotal", 0L);//查询已中奖的序列号的总条数
        String userId = commonUtils.getUserId();//用户Id
        List<String> user = new ArrayList<>();
        user.add(userId);
        List<GoldserialVo> notVoList = new ArrayList<>();//查询所有的序列号集合
        List<GoldserialVo> voList = new ArrayList<>();//查询已中奖的序列号集合
        TRebateSetInfo tRebateSetInfo = tRebateSetInfoMapper.selectTRebateSetInfoById("1");//默认id为1
        TStatisticInfo tStatisticInfo = tStatisticInfoMapper.selectTStatisticInfoByUserIds(user, "", null, null);//查询我的累计交易额度
        TStatisticInfo terrace = tStatisticInfoMapper.selectTStatisticInfoForTotal();//平台累计交易金额
        resultMap.put("MyTransMoney", tStatisticInfo == null ? BigDecimal.ZERO : tStatisticInfo.getMyTransMoney());//我实时交易总额度
        resultMap.put("dealGold", tRebateSetInfo == null ? BigDecimal.ZERO : tRebateSetInfo.getDealGold());//交易金金币
        resultMap.put("awardGold", tRebateSetInfo == null ? BigDecimal.ZERO : tRebateSetInfo.getAwardGold());//奖励金金币
        resultMap.put("platformAmount", terrace == null ? BigDecimal.ZERO : terrace.getMyTransMoney());//平台实时累计交易额
        //查询交易金序列号
        if (exchangeDto.getTransType().equals("0")) {
            TGoldDealSerialInfo dealMax = tGoldDealSerialInfoMapper.queryDealMax();
            TGoldDealSerialInfo dealExchangeMax = tGoldDealSerialInfoMapper.queryDealExchangeMax();
            resultMap.put("dealAndAwardExchangeMax", null == dealExchangeMax ? BigDecimal.ZERO : dealExchangeMax.getSerialNo());//平台奖励金已兑奖最大编码
            resultMap.put("dealAndAwardMax", null == dealMax ? BigDecimal.ZERO : dealMax.getSerialNo());//上期中奖编号/平台奖励金已开奖编码
            //计算下期开奖进度(平台发放金币)
            //terrace.getMyTransMoney()平台累计用户余额
            //tRebateSetInfo.getPlatformAward()平台累计达到xx金额（发放奖励金）
            //.divide(tRebateSetInfo.getPlatformAward(),2,BigDecimal.ROUND_HALF_DOWN)
            BigDecimal platformAward = (terrace == null ? BigDecimal.ZERO : terrace.getMyTransMoney()).divideAndRemainder(tRebateSetInfo.getPlatformDeal())[1].divide(tRebateSetInfo.getPlatformDeal(), 2, BigDecimal.ROUND_HALF_DOWN);
            resultMap.put("platformDealAndAward", new BigDecimal(platformAward.multiply(BigDecimal.valueOf(100L)).stripTrailingZeros().toPlainString()));//开奖进度百分比

            //计算获取下个序列号进度
            //tStatisticInfo.getMyTransMoney()//用户累计达到金额（交易金）
            //tRebateSetInfo.getUserDeal//用户累计达到金额配置(交易金)
            //divide(tRebateSetInfo.getUserDeal(),2,BigDecimal.ROUND_HALF_DOWN)
            BigDecimal userAward = tStatisticInfo == null ? BigDecimal.ZERO : tStatisticInfo.getMyTransMoney().divideAndRemainder(tRebateSetInfo.getUserDeal())[1].divide(tRebateSetInfo.getUserDeal(), 2, BigDecimal.ROUND_HALF_DOWN);
            resultMap.put("userDealAndAward", new BigDecimal(userAward.multiply(BigDecimal.valueOf(100L)).stripTrailingZeros().toPlainString()));//获取下一个序列号百分比

            //我个人可消费所有序列号
            resultMap.put("dealAndAwardCount", tGoldDealSerialInfoMapper.queryDealCount(userId));

            //平台动态所有已兑奖的序列号
            List<GoldserialVo> goldserialVo = tGoldDealSerialInfoMapper.queryDealRoll();
            Optional.ofNullable(goldserialVo).ifPresent(lists -> {
                resultMap.put("dealAndAwardRollTotal", new PageInfo(lists).getTotal());//平台动态所有已兑奖的序列号总条数
                lists.stream().forEach(bean -> {
                    bean.setExchangeShow(Optional.ofNullable(YesOrNoEnums.getEnumsByCode(bean.getExchange())).map(item -> item.getValue()).orElse(bean.getExchange()));
                });
            });
            resultMap.put("dealAndAwardRollList", goldserialVo);//平台动态所有已兑奖的序列号集合

            TGoldDealSerialInfo tGoldDealSerialInfo = new TGoldDealSerialInfo();
            tGoldDealSerialInfo.setUserId(userId);
            tGoldDealSerialInfo.setExchange(YesOrNoEnums.NO.getCode());
            PageUtil.startPage(exchangeDto.getPageNum(), exchangeDto.getPageSize());
            //查询我的奖励金序列号
            List<TGoldDealSerialInfo> awardList = tGoldDealSerialInfoMapper.selectTGoldDealSerialInfoList(tGoldDealSerialInfo);
            Optional.ofNullable(awardList).ifPresent(lists -> {
                resultMap.put("notTotal", new PageInfo(lists).getTotal());//查询我的奖励金序列号总条数
                lists.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(Optional.ofNullable(YesOrNoEnums.getEnumsByCode(bean.getExchange())).map(item -> item.getValue()).orElse(bean.getExchange()));
                    notVoList.add(vo);
                });
            });
            tGoldDealSerialInfo.setExchange(YesOrNoEnums.YES.getCode());
            PageUtil.startPage(exchangeDto.getPageNumw(), exchangeDto.getPageSizew());
            //查询我的奖励金序列号已中奖
            List<TGoldDealSerialInfo> tGoldAwardSerialInfos = tGoldDealSerialInfoMapper.selectTGoldDealSerialInfoDesc(tGoldDealSerialInfo);
            Optional.ofNullable(tGoldAwardSerialInfos).ifPresent(lists -> {
                resultMap.put("yesTotal", new PageInfo(lists).getTotal());//查询我的奖励金序列号已中奖总条数
                lists.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(Optional.ofNullable(YesOrNoEnums.getEnumsByCode(bean.getExchange())).map(item -> item.getValue()).orElse(bean.getExchange()));
                    voList.add(vo);
                });
            });
        } else if (exchangeDto.getTransType().equals("1")) {//查询奖励金的序列号
            TGoldAwardSerialInfo awardMax = tGoldAwardSerialInfoMapper.queryAwardMax();
            TGoldAwardSerialInfo awardExchangeMax = tGoldAwardSerialInfoMapper.queryAwardExchangeMax();
            resultMap.put("dealAndAwardExchangeMax", null == awardExchangeMax ? BigDecimal.ZERO : awardExchangeMax.getSerialNo());//平台奖励金已兑奖最大编码
            resultMap.put("dealAndAwardMax", null == awardMax ? BigDecimal.ZERO : awardMax.getSerialNo());//上期中奖编号/平台奖励金已开奖编码
            //计算下期开奖进度(平台发放金币)
            BigDecimal platformAward = terrace.getMyTransMoney().divideAndRemainder(tRebateSetInfo.getPlatformAward())[1].divide(tRebateSetInfo.getPlatformAward(), 2, BigDecimal.ROUND_HALF_DOWN);
            resultMap.put("platformDealAndAward", new BigDecimal(platformAward.multiply(BigDecimal.valueOf(100L)).stripTrailingZeros().toPlainString()));//开奖进度百分比
            //计算获取下个序列号进度
            BigDecimal userAward = (tStatisticInfo == null ? BigDecimal.ZERO : tStatisticInfo.getMyTransMoney()).divideAndRemainder(tRebateSetInfo.getUserAward())[1].divide(tRebateSetInfo.getUserAward(), 2, BigDecimal.ROUND_HALF_DOWN);
            resultMap.put("userDealAndAward", new BigDecimal(userAward.multiply(BigDecimal.valueOf(100L)).stripTrailingZeros().toPlainString()));//获取下一个序列号百分比

            //我个人可消费所有序列号
            resultMap.put("dealAndAwardCount", tGoldAwardSerialInfoMapper.queryAwardCount(userId));

            //平台动态所有已兑奖的序列号
            List<GoldserialVo> goldserialVo = tGoldAwardSerialInfoMapper.queryAwardRoll();
            Optional.ofNullable(goldserialVo).ifPresent(lists -> {
                resultMap.put("dealAndAwardRollTotal", new PageInfo(lists).getTotal());//平台动态所有已兑奖的序列号总条数
                lists.stream().forEach(bean -> {
                    bean.setExchangeShow(Optional.ofNullable(YesOrNoEnums.getEnumsByCode(bean.getExchange())).map(item -> item.getValue()).orElse(bean.getExchange()));
                });
            });
            resultMap.put("dealAndAwardRollList", goldserialVo);//平台动态所有已兑奖的序列号集合

            TGoldAwardSerialInfo tGoldAwardSerialInfo = new TGoldAwardSerialInfo();
            tGoldAwardSerialInfo.setUserId(userId);
            tGoldAwardSerialInfo.setExchange(YesOrNoEnums.NO.getCode());
            PageUtil.startPage(exchangeDto.getPageNum(), exchangeDto.getPageSize());
            //查询我的奖励金序列号
            List<TGoldAwardSerialInfo> awardList = tGoldAwardSerialInfoMapper.selectTGoldAwardSerialInfoList(tGoldAwardSerialInfo);
            Optional.ofNullable(awardList).ifPresent(lists -> {
                resultMap.put("notTotal", new PageInfo(lists).getTotal());//查询我的奖励金序列号总条数
                lists.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(Optional.ofNullable(YesOrNoEnums.getEnumsByCode(bean.getExchange())).map(item -> item.getValue()).orElse(bean.getExchange()));
                    notVoList.add(vo);
                });
            });
            tGoldAwardSerialInfo.setExchange(YesOrNoEnums.YES.getCode());
            PageUtil.startPage(exchangeDto.getPageNumw(), exchangeDto.getPageSizew());
            //查询我的奖励金序列号已中奖
            List<TGoldAwardSerialInfo> tGoldAwardSerialInfos = tGoldAwardSerialInfoMapper.selectTGoldAwardSerialInfoDesc(tGoldAwardSerialInfo);
            Optional.ofNullable(tGoldAwardSerialInfos).ifPresent(lists -> {
                resultMap.put("yesTotal", new PageInfo(lists).getTotal());//查询我的奖励金序列号已中奖总条数
                lists.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(Optional.ofNullable(YesOrNoEnums.getEnumsByCode(bean.getExchange())).map(item -> item.getValue()).orElse(bean.getExchange()));
                    voList.add(vo);
                });
            });
        }

        resultMap.put("notVoList", notVoList);//我的交易金抽奖中【奖励金】
        resultMap.put("yesList", voList);//我的交易金已中奖【奖励金】
        return resultMap;
    }

    //校验支付密码
    @Override
    public JSONObject checkPayPassword(UserDto userDto) throws Exception {
        if (StringUtils.isEmpty(userDto.getPayPassword())) {
            throw new RuntimeException("支付密码不能为空");
        }
        String userId = commonUtils.getUserId();
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(userId);
        JSONObject jo = new JSONObject();
        String payPassword = SaltUtils.salt(userDto.getPayPassword(), user.getPaySalt());
        if (payPassword.equals(user.getPayPassword())) {
            jo.put("result", "校验通过！");
        } else {
            throw new RuntimeException("支付密码错误，请重新输入！");
        }
        return jo;
    }

    //查询划拨记录列表
    @Override
    public Map<String, Object> queryTerminalTransRecordList(TerminalTransRecordDto terminalTransRecordDto) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String userId = commonUtils.getUserId();
        TTerminalTransInfo mapper = new TTerminalTransInfo();
        if (YesOrNoEnums.YES.getCode().equals(terminalTransRecordDto.getTransType())){//划拨类型（0：划拨，1：划回）
            mapper.setTransInUserId(userId);//接收人
            mapper.setTransType(YesOrNoEnums.YES.getCode());
        }else {
            mapper.setTransInUserId(userId);//接收人
            mapper.setTransType(YesOrNoEnums.NO.getCode());
        }

        PageUtil.startPage(terminalTransRecordDto);
        List<TTerminalTransInfo> list = terminalTransInfoMapper.selectTTerminalTransInfoList(mapper);
        List<TerminalTransRecordVo> voList = new ArrayList<TerminalTransRecordVo>();
        resultMap.put("total", 0L);

        Optional.ofNullable(list).ifPresent(lists -> {
            resultMap.put("total", new PageInfo(lists).getTotal());
            lists.stream().forEach(bean -> {
                TerminalTransRecordVo vo = new TerminalTransRecordVo();
                BeanUtils.copyProperties(bean, vo);
                vo.setTerminalTransId(bean.getId());
                if (StringUtils.isNotEmpty(vo.getTransOutUserId())) {//划拨人
                    TUserInfo outUser = userInfoMapper.selectTUserInfoByUserId(vo.getTransOutUserId());
                    vo.setTransOutUserName(outUser.getUserName());
                    vo.setTransStatusShow(Optional.ofNullable(TransStatusEnum.getEnumsByCode(vo.getTransStatus())).map(item -> item.getValue()).orElse(vo.getTransStatus()));
                }
                if (StringUtils.isNotEmpty(vo.getTransInUserId())) { //划回人
                    TUserInfo inUser = userInfoMapper.selectTUserInfoByUserId(vo.getTransInUserId());
                    vo.setTransStatusShow(Optional.ofNullable(TransStatusEnum.getEnumsByCode(vo.getTransStatus())).map(item -> item.getValue()).orElse(vo.getTransStatus()));
                    vo.setTransInUserName(inUser.getUserName());
                }
                voList.add(vo);
            });
        });

        resultMap.put("list", voList);
        return resultMap;
    }

    //划拨（确认）
    @Override
    @Transactional
    public void terminalTransferConfirm(TerminalManageDto terminalManageDto) throws Exception {
        Date date = DateUtils.getNowDate();
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(commonUtils.getUserId());
        //更新划拨记录表
        TTerminalTransInfo trans = terminalTransInfoMapper.selectTTerminalTransInfoById(terminalManageDto.getTerminalTransId());
        trans.setTransStatus(TransStatusEnum.HAS_CONFIIRM.getCode());
        trans.setTransInTime(DateUtils.getNowDate());
        terminalTransInfoMapper.updateTTerminalTransInfo(trans);

        //更新终端的userId
        TTerminalInfo mapper = new TTerminalInfo();
        mapper.setSnCode(trans.getSnCode());
        List<TTerminalInfo> list = terminalInfoMapper.selectTTerminalInfoList(mapper);
        TTerminalInfo terminal = Optional.ofNullable(list).get().get(0);
        if (!TransStatusEnum.WAIT_CONFIIRM.getCode().equals(terminal.getTransStatus())) {
            log.info("该终端状态为:" + TransStatusEnum.getEnumsByCode(terminal.getTransStatus()).getValue() + "，不能再操作，终端号：" + terminal.getSnCode());
            throw new RuntimeException("该终端状态为:" + TransStatusEnum.getEnumsByCode(terminal.getTransStatus()).getValue() + "，不能再操作");
        }

        //更新统计表的划入划出终端数、划入终端数、我的终端数

        TStatisticInfo statisticIn = tStatisticInfoMapper.selectTStatisticInfoForCurrentDay(trans.getTransInUserId(), terminal.getBrandId()); //接收人
        if (null == statisticIn) {
            TUserInfo inUser = userInfoMapper.selectTUserInfoByUserId(trans.getTransInUserId());
            statisticIn = commonUtils.generateStatisticInfo(inUser, date, terminal.getBrandId());
            tStatisticInfoMapper.insertTStatisticInfo(statisticIn);
        }
        if (StringUtils.isEmpty(terminal.getUserId())) { //说明是平台初始化划拨，将终端初始金额挂在接收人的统计数据化中
            /*statisticIn.setMyTransMoney(statisticIn.getMyTransMoney().add(terminal.getTerminalGmv())); //交易额
            statisticIn.setMyTransNum(statisticIn.getMyTransNum().add(BigDecimal.ONE)); //交易笔数
            TUserInfo inUser = userInfoMapper.selectTUserInfoByUserId(trans.getTransInUserId());
            inUser.setTotalTransAmount(inUser.getTotalTransAmount().add(terminal.getTerminalGmv()));
            userInfoMapper.updateTUserInfo(inUser);*/
            //模拟生成一条第三方终端交易流水记录
            TTerminalTransFlowInfo flow = new TTerminalTransFlowInfo();
            flow.setId(IdUtils.simpleUUID());
            flow.setCreateTime(DateUtils.getNowDate());
            flow.setIsValid(YesOrNoEnums.YES.getCode());
            flow.setHandleStaus(HandleStausEnum.NO_HANDLE.getCode());
            flow.setHandleResult("初始化交易额");
            flow.setAgentId("000000000");
            flow.setMachineType("2");
            flow.setOrderId(flow.getId());
            flow.setSysno(flow.getId());
            flow.setMerName(user.getUserName() + user.getUserPhone());
            flow.setMerId(flow.getId());
            flow.setSnCode(terminal.getSnCode());
            flow.setTransAmount(terminal.getTerminalGmv().multiply(BigDecimal.valueOf(100)));
            flow.setMerSigeFee(BigDecimal.ZERO);
            flow.setExtractionFee(BigDecimal.ZERO);
            flow.setSettlementCycle("0");
            flow.setPayType("1");
            flow.setCardType("1");
            flow.setTransCategory("2");
            flow.setCardNo(flow.getId());
            terminalTransFlowInfoMapper.insertTTerminalTransFlowInfo(flow);
        } else { //记录划出人的统计信息
            TStatisticInfo statisticOut = tStatisticInfoMapper.selectTStatisticInfoForCurrentDay(trans.getTransOutUserId(), terminal.getBrandId()); //划出人
            if (null == statisticOut) {
                TUserInfo outUser = userInfoMapper.selectTUserInfoByUserId(trans.getTransOutUserId());
                statisticOut = commonUtils.generateStatisticInfo(outUser, date, terminal.getBrandId());
                tStatisticInfoMapper.insertTStatisticInfo(statisticOut);
            }
            statisticOut.setMyTerminalNum(statisticOut.getMyTerminalNum().subtract(BigDecimal.ONE));
            statisticOut.setMyOutTerminalNum(statisticOut.getMyOutTerminalNum().add(BigDecimal.ONE));
            tStatisticInfoMapper.updateTStatisticInfo(statisticOut);
        }
        statisticIn.setMyTerminalNum(statisticIn.getMyTerminalNum().add(BigDecimal.ONE));
        statisticIn.setMyInTerminalNum(statisticIn.getMyInTerminalNum().add(BigDecimal.ONE));
        tStatisticInfoMapper.updateTStatisticInfo(statisticIn);

        terminal.setUserId(trans.getTransInUserId());
        terminal.setUserName(user.getUserName());
        terminal.setPhone(user.getUserPhone());
        terminal.setTransStatus(TransStatusEnum.HAS_CONFIIRM.getCode());
        terminal.setTerminalType(TerminalTypeEnum.TRANS.getCode());
        terminal.setRemark(trans.getRemark());
        terminalInfoMapper.updateTTerminalInfo(terminal);
    }

    //划拨（拒绝）
    @Override
    @Transactional
    public void terminalTransferRefuse(TerminalManageDto terminalManageDto) throws Exception {
        //更新划拨记录表
        TTerminalTransInfo trans = terminalTransInfoMapper.selectTTerminalTransInfoById(terminalManageDto.getTerminalTransId());
        trans.setTransStatus(TransStatusEnum.HAS_REFUSE.getCode());
        trans.setTransInTime(DateUtils.getNowDate());
        terminalTransInfoMapper.updateTTerminalTransInfo(trans);

        //更新终端的userId
        TTerminalInfo mapper = new TTerminalInfo();
        mapper.setSnCode(trans.getSnCode());
        List<TTerminalInfo> list = terminalInfoMapper.selectTTerminalInfoList(mapper);
        TTerminalInfo terminal = Optional.ofNullable(list).get().get(0);
        terminal.setTransStatus(TransStatusEnum.HAS_REFUSE.getCode());
        terminalInfoMapper.updateTTerminalInfo(terminal);
    }


    //兑换商城用户余额
    @Override
    public Map<String, Object> userBalance() throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        String userId = commonUtils.getUserId();
        TUserInfo tUserInfo = userInfoMapper.selectTUserInfoByUserId(userId);
        //我的余额
        BigDecimal balance = tUserInfo.getBalanceSum().subtract(tUserInfo.getBalanceWithdraw()).subtract(tUserInfo.getBalanceUse());
        returnMap.put("balance", balance);
        //我的金币
        BigDecimal gold = tUserInfo.getGoldSum().subtract(tUserInfo.getGoldWithdraw()).subtract(tUserInfo.getGoldExchange());
        returnMap.put("gold", gold);

        //我的积分
        BigDecimal integral = tUserInfo.getIntegralSum().subtract(tUserInfo.getIntegralExchange());
        returnMap.put("integral", integral);
        //我的可以可消费交易金序列号
        returnMap.put("dealBalance", goldDealSerialInfoMapper.queryDealCount(userId));
        //我的可以可消费奖励金序列号
        returnMap.put("awardBalance", goldAwardSerialInfoMapper.queryAwardCount(userId));
        return returnMap;
    }

    //(我的收益)我的余额
    @Override
    public Map<String, Object> queryMyIncome(UserDefaultDto userDefaultDto) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        String userId = commonUtils.getUserId();
        TUserInfo userInfo = userInfoMapper.selectTUserInfoByUserId(userId);
        //我的余额
        BigDecimal balance = (userInfo.getBalanceSum().subtract(userInfo.getBalanceWithdraw())).subtract(userInfo.getBalanceUse());
        returnMap.put("balance", balance);
        //我的金币
        BigDecimal gold = (userInfo.getGoldSum().subtract(userInfo.getGoldWithdraw())).subtract(userInfo.getGoldExchange());
        returnMap.put("gold", gold);
        //我的积分
        BigDecimal integral = userInfo.getIntegralSum().subtract(userInfo.getIntegralExchange());
        returnMap.put("integral", integral);

        //我的交易金序列号
        returnMap.put("deal", tGoldDealSerialInfoMapper.queryDealCount(userId));

        //我的奖励金序列号
        returnMap.put("award", tGoldAwardSerialInfoMapper.queryAwardCount(userId));

        //查询我的收益基础状态
        List<String> transOperType = new ArrayList<>();
        transOperType.add(TransOperTypeEnum.YUE_1004.getCode());
        transOperType.add(TransOperTypeEnum.YUE_1005.getCode());
        transOperType.add(TransOperTypeEnum.YUE_1006.getCode());
        transOperType.add(TransOperTypeEnum.YUE_1007.getCode());
        transOperType.add(TransOperTypeEnum.YUE_1008.getCode());
        transOperType.add(TransOperTypeEnum.YUE_1009.getCode());
        transOperType.add(TransOperTypeEnum.YUE_1010.getCode());

        TUserDefaultInfo today = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), transOperType, TransTypeEnum.YUE.getCode(), "1");//查询今日收益
        returnMap.put("today", today == null ? BigDecimal.ZERO : today.getTransAmount());//查询今日收益

        TUserDefaultInfo yesterday = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), transOperType, TransTypeEnum.YUE.getCode(), "2");//查询昨天收益
        returnMap.put("yesterday", yesterday == null ? BigDecimal.ZERO : yesterday.getTransAmount());//查询昨天收益

        TUserDefaultInfo thisMonth = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), transOperType, TransTypeEnum.YUE.getCode(), "3");//查询本月收益
        returnMap.put("thisMonth", thisMonth == null ? BigDecimal.ZERO : thisMonth.getTransAmount());//查询本月收益

        TUserDefaultInfo lastMonth = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), transOperType, TransTypeEnum.YUE.getCode(), "4");//查询上月收益
        returnMap.put("lastMonth", lastMonth == null ? BigDecimal.ZERO : lastMonth.getTransAmount());//查询上月收益
        //returnMap.put("lastMonth", Optional.ofNullable(Optional.ofNullable(lastMonth).orElse(new TUserDefaultInfo()).getTransAmount()).orElse(BigDecimal.ZERO));//查询上月收益
        return returnMap;
    }

    /*我的金币详情列表*/
    @Override
    public Map<String,Object> queryMyGoldDetails(UserDefaultDto userDefaultDto) throws Exception {
        List<UserDefaultVo> listVo = new ArrayList<>();
        String userId = commonUtils.getUserId();
        userDefaultDto.setUserId(userId);
        PageUtil.startPage(userDefaultDto);
        Map<String,Object> returnMap = new HashMap<>();
        userDefaultDto.setTransType(TransTypeEnum.JINBI.getCode());//金币
        userDefaultDto.setTransOperType(TransOperTypeEnum.JINBI_3001.getCode() + "," + //序列号兑换（入）
                TransOperTypeEnum.JINBI_3002.getCode() + "," +  //出售商品（入）
                TransOperTypeEnum.JINBI_3003.getCode() + "," +//商品兑换（出）
                TransOperTypeEnum.JINBI_3004.getCode());    //兑换现金（出）
        List<TUserDefaultInfo> tUserDefaultInfos = userDefaultInfoMapper.queryMyCommonDetails(userDefaultDto);
        returnMap.put("total",new PageInfo(tUserDefaultInfos).getTotal());
        Optional.ofNullable(tUserDefaultInfos).ifPresent(userDefault -> {
            userDefault.stream().forEach(bean -> {
                UserDefaultVo vo = new UserDefaultVo();
                BeanUtils.copyProperties(bean, vo);
                vo.setTransTypeShow(Optional.ofNullable(TransTypeEnum.getEnumsByCode(vo.getTransType())).map(item -> item.getValue()).orElse(vo.getTransType()));
                vo.setTransOperTypeShow(Optional.ofNullable(TransOperTypeEnum.getEnumsByCode(vo.getTransOperType())).map(item -> item.getValue()).orElse(vo.getTransOperType()));
                vo.setGoldTypeShow(vo.getGoldType() != null ? vo.getGoldType().equals("1") ? "交易金金币" : vo.getGoldType().equals("2") ? "奖励金金币" : null : "");
                listVo.add(vo);
            });
        });
        TUserInfo userInfo = userInfoMapper.selectTUserInfoByUserId(userId);
        BigDecimal gold = (userInfo.getGoldSum().subtract(userInfo.getGoldWithdraw())).subtract(userInfo.getGoldExchange());//金币
        returnMap.put("gold",gold);
        returnMap.put("lists",listVo);
        return returnMap;
    }

    /*我的积分详情列表*/
    @Override
    public Map<String,Object> queryMyIntegralDetails(UserDefaultDto userDefaultDto) throws Exception {
        Map<String,Object> returnMap = new HashMap<>();
        List<UserDefaultVo> listVo = new ArrayList<>();
        String userId = commonUtils.getUserId();
        userDefaultDto.setUserId(userId);
        PageUtil.startPage(userDefaultDto);
        userDefaultDto.setTransType(TransTypeEnum.JIFEN.getCode());//积分
        userDefaultDto.setTransOperType(TransOperTypeEnum.JIFEN_2001.getCode() + "," + //激活奖励
                TransOperTypeEnum.JIFEN_2002.getCode() + "," +  //积分出售商品
                TransOperTypeEnum.JIFEN_2003.getCode());    //积分商品兑换
        List<TUserDefaultInfo> tUserDefaultInfos = userDefaultInfoMapper.queryMyCommonDetails(userDefaultDto);
        returnMap.put("total",new PageInfo(tUserDefaultInfos).getTotal());
        Optional.ofNullable(tUserDefaultInfos).ifPresent(userDefault -> {
            userDefault.stream().forEach(bean -> {
                UserDefaultVo vo = new UserDefaultVo();
                BeanUtils.copyProperties(bean, vo);
                vo.setTransTypeShow(Optional.ofNullable(TransTypeEnum.getEnumsByCode(vo.getTransType())).map(item -> item.getValue()).orElse(vo.getTransType()));
                vo.setTransOperTypeShow(Optional.ofNullable(TransOperTypeEnum.getEnumsByCode(vo.getTransOperType())).map(item -> item.getValue()).orElse(vo.getTransOperType()));
                vo.setGoldTypeShow(vo.getGoldType() != null ? vo.getGoldType().equals("1") ? "交易金金币" : vo.getGoldType().equals("2") ? "奖励金金币" : null : "");
                listVo.add(vo);
            });
        });
        TUserInfo userInfo = userInfoMapper.selectTUserInfoByUserId(userId);
        BigDecimal integral = userInfo.getIntegralSum().subtract(userInfo.getIntegralExchange());
        returnMap.put("lists",listVo);
        returnMap.put("integral",integral);
        return returnMap;
    }


    //我的收益，交易金详情列表
    @Override
    public Map<String, Object> queryMyDealAndGoldDetails(UserDefaultDto userDefaultDto) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        String userId = commonUtils.getUserId();
        int dealCount = tGoldDealSerialInfoMapper.queryDealCount(userId);//我的交易金
        returnMap.put("dealCount", dealCount);
        PageUtil.startPage(userDefaultDto);
        if (userDefaultDto.getReleaseType().equals("0")) {//待释放
            List<TGoldDealSerialInfo> tGoldDealSerialInfos = tGoldDealSerialInfoMapper.selectTGoldDealExchangeTimeList(userId, "1", userDefaultDto.getCreateTime(), "");//待释放的序列号
            List<GoldserialVo> goldVo = new ArrayList<>();
            Optional.ofNullable(tGoldDealSerialInfos).ifPresent(mpa -> {
                returnMap.put("total", new PageInfo(mpa).getTotal());
                mpa.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(vo.getExchange() == null ? "" : (vo.getExchange().equals("0") ? "是" : "否"));
                    goldVo.add(vo);
                });
            });
            returnMap.put("lists", goldVo);//待释放的序列号

        } else if (userDefaultDto.getReleaseType().equals("1")) {//已释放
            List<TGoldDealSerialInfo> tGoldDealSerials = tGoldDealSerialInfoMapper.selectTGoldDealExchangeTimeList(userId, "0", "", userDefaultDto.getCreateTime());//已转换的序列号
            List<GoldserialVo> goldReleaseVo = new ArrayList<>();
            Optional.ofNullable(tGoldDealSerials).ifPresent(mpa -> {
                returnMap.put("total", new PageInfo(mpa).getTotal());
                mpa.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(vo.getExchange() == null ? "" : (vo.getExchange().equals("0") ? "是" : "否"));
                    goldReleaseVo.add(vo);
                });
            });
            returnMap.put("lists", goldReleaseVo);//已转换的序列号
        } else if (userDefaultDto.getReleaseType().equals("2")) {//已兑换
            //已兑换商品
            List<String> transOperType = new ArrayList<>();
            transOperType.add(TransOperTypeEnum.JIAOYIJIN_4002.getCode());
            transOperType.add(TransOperTypeEnum.JIAOYIJIN_4003.getCode());
            List<TUserDefaultInfo> tUserDefaultInfos = userDefaultInfoMapper.queryMySerialDetails(userId, transOperType, TransTypeEnum.JIAOYIJIN.getCode(), userDefaultDto.getCreateTime() + "");
            List<UserDefaultVo> listVo = new ArrayList<>();
            Optional.ofNullable(tUserDefaultInfos).ifPresent(map -> {
                returnMap.put("total", new PageInfo(map).getTotal());
                map.stream().forEach(bean -> {
                    UserDefaultVo vo = new UserDefaultVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setTransTypeShow(Optional.ofNullable(TransTypeEnum.getEnumsByCode(vo.getTransType())).map(item ->item.getValue()).orElse(vo.getTransType()));
                    vo.setTransOperTypeShow(Optional.ofNullable(TransOperTypeEnum.getEnumsByCode(vo.getTransOperType())).map(item ->item.getValue()).orElse(vo.getTransOperType()));
                    listVo.add(vo);
                });
            });
            returnMap.put("lists", listVo);//已兑换商品
        }
        return returnMap;
    }


    //我的收益，奖励金详情列表
    @Override
    public Map<String, Object> queryMyAwardAndGoldDetails(UserDefaultDto userDefaultDto) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        String userId = commonUtils.getUserId();
        int awardCount = tGoldAwardSerialInfoMapper.queryAwardCount(userId);//我的奖励金
        returnMap.put("awardCount", awardCount);
        PageUtil.startPage(userDefaultDto);
        if (userDefaultDto.getReleaseType().equals("0")) {//待释放
            List<TGoldAwardSerialInfo> tGoldDealSerialInfos = tGoldAwardSerialInfoMapper.selectTGoldAwardExchangeTimeList(userId, "1", userDefaultDto.getCreateTime(), "");//待释放的序列号
            List<GoldserialVo> goldVo = new ArrayList<>();
            Optional.ofNullable(tGoldDealSerialInfos).ifPresent(mpa -> {
                returnMap.put("total", new PageInfo(mpa).getTotal());
                mpa.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(vo.getExchange() == null ? "" : (vo.getExchange().equals("0") ? "是" : "否"));
                    goldVo.add(vo);
                });
            });
            returnMap.put("lists", goldVo);//待释放的序列号
            PageUtil.startPage(userDefaultDto);
        } else if (userDefaultDto.getReleaseType().equals("1")) {//已释放
            List<TGoldAwardSerialInfo> tGoldDealSerials = tGoldAwardSerialInfoMapper.selectTGoldAwardExchangeTimeList(userId, "0", "", userDefaultDto.getCreateTime());//已转换的序列号
            List<GoldserialVo> goldReleaseVo = new ArrayList<>();
            Optional.ofNullable(tGoldDealSerials).ifPresent(mpa -> {
                returnMap.put("total", new PageInfo(mpa).getTotal());
                mpa.stream().forEach(bean -> {
                    GoldserialVo vo = new GoldserialVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setExchangeShow(vo.getExchange() == null ? "" : (vo.getExchange().equals("0") ? "是" : "否"));
                    goldReleaseVo.add(vo);
                });
            });
            returnMap.put("lists", goldReleaseVo);//已转换的序列号
        } else if (userDefaultDto.getReleaseType().equals("2")) {//已兑换
            //已兑换商品
            List<String> transOperType = new ArrayList<>();
            transOperType.add(TransOperTypeEnum.JIANGLIJIN_5002.getCode());
            transOperType.add(TransOperTypeEnum.JIANGLIJIN_5003.getCode());
            List<TUserDefaultInfo> tUserDefaultInfos = userDefaultInfoMapper.queryMySerialDetails(userId, transOperType, TransTypeEnum.JIANGLIJIN.getCode(), userDefaultDto.getCreateTime() + "");
            List<UserDefaultVo> listVo = new ArrayList<>();
            Optional.ofNullable(tUserDefaultInfos).ifPresent(map -> {
                returnMap.put("total", new PageInfo(map).getTotal());
                map.stream().forEach(bean -> {
                    UserDefaultVo vo = new UserDefaultVo();
                    BeanUtils.copyProperties(bean, vo);
                    vo.setTransTypeShow(Optional.ofNullable(TransTypeEnum.getEnumsByCode(vo.getTransType())).map(item ->item.getValue()).orElse(vo.getTransType()));
                    vo.setTransOperTypeShow(Optional.ofNullable(TransOperTypeEnum.getEnumsByCode(vo.getTransOperType())).map(item ->item.getValue()).orElse(vo.getTransOperType()));
                    listVo.add(vo);
                });
            });
            returnMap.put("lists", listVo);//已兑换商品
        }
        return returnMap;
    }

    /*总收益分析*/
    @Override
    public Map<String, Object> queryMyTotalRevenueDetails(UserDefaultDto userDefaultDto) throws Exception {
        String userId = commonUtils.getUserId();
        Map<String, Object> returnMap = new HashMap<>();
        //查询我的收益基础状态
        List<String> transOperType = new ArrayList<>();
        transOperType.add(TransOperTypeEnum.YUE_1004.getCode());//商户收益(激活奖励)
        transOperType.add(TransOperTypeEnum.YUE_1005.getCode());//直接收益
        transOperType.add(TransOperTypeEnum.YUE_1006.getCode());//下级收益
        transOperType.add(TransOperTypeEnum.YUE_1007.getCode());//采购收益
        transOperType.add(TransOperTypeEnum.YUE_1008.getCode());//提现收益
        transOperType.add(TransOperTypeEnum.YUE_1009.getCode());//办公补贴
        TUserDefaultInfo today = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), transOperType, TransTypeEnum.YUE.getCode(), "");//查询总收益
        returnMap.put("today", today == null ? BigDecimal.ZERO : today.getTransAmount());//查询总收益

        TUserDefaultInfo activateAward = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.YUE_1004.getCode(), TransTypeEnum.YUE.getCode(), "");//查询商户收益激活奖励
        returnMap.put("activateAward", activateAward == null ? BigDecimal.ZERO : activateAward.getTransAmount());//商户奖励金/也是商户总收益

        TUserDefaultInfo integral = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.JIFEN_2001.getCode(), TransTypeEnum.JIFEN.getCode(), "");//商户收益 激活奖励
        returnMap.put("integral", integral == null ? BigDecimal.ZERO : integral.getTransAmount());//商户收益 激活奖励

        List<String> shareProfit = new ArrayList<>();
        shareProfit.add(TransOperTypeEnum.YUE_1005.getCode());//直接收益
        shareProfit.add(TransOperTypeEnum.YUE_1006.getCode());//下级收益
        TUserDefaultInfo shareProfitList = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), shareProfit, TransTypeEnum.YUE.getCode(), "");//分润总收益
        returnMap.put("shareProfitList", shareProfitList == null ? BigDecimal.ZERO : shareProfitList.getTransAmount());//分润总收益

        TUserDefaultInfo earnings = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.YUE_1005.getCode(), TransTypeEnum.YUE.getCode(), "");//直接收益
        returnMap.put("earnings", earnings == null ? BigDecimal.ZERO : earnings.getTransAmount());//直接收益

        TUserDefaultInfo juniorEarnings = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.YUE_1006.getCode(), TransTypeEnum.YUE.getCode(), "");//下级收益
        returnMap.put("juniorEarnings", juniorEarnings == null ? BigDecimal.ZERO : juniorEarnings.getTransAmount());//下级收益


        List<String> tutorType = new ArrayList<>();
        tutorType.add(TransOperTypeEnum.YUE_1007.getCode());//采购收益
        tutorType.add(TransOperTypeEnum.YUE_1008.getCode());//提现收益
        tutorType.add(TransOperTypeEnum.YUE_1009.getCode());//办公补贴
        TUserDefaultInfo tutor = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), tutorType, TransTypeEnum.YUE.getCode(), "");//导师收益
        returnMap.put("tutor", tutor == null ? BigDecimal.ZERO : tutor.getTransAmount());//导师收益

        TUserDefaultInfo purchase = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.YUE_1007.getCode(), TransTypeEnum.YUE.getCode(), "");//采购收益
        returnMap.put("purchase", purchase == null ? BigDecimal.ZERO : purchase.getTransAmount());//采购收益

        TUserDefaultInfo deposit = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.YUE_1008.getCode(), TransTypeEnum.YUE.getCode(), "");//提现收益
        returnMap.put("deposit", deposit == null ? BigDecimal.ZERO : deposit.getTransAmount());//提现收益

        TUserDefaultInfo work = userDefaultInfoMapper.queryMoneyIf(userId, userDefaultDto.getBrandId(), TransOperTypeEnum.YUE_1009.getCode(), TransTypeEnum.YUE.getCode(), "");//办公收益
        returnMap.put("work", work == null ? BigDecimal.ZERO : work.getTransAmount());//办公收益
        return returnMap;
    }

    /*收益明细*/
    @Override
    public Map<String, Object> queryEarningsDetail(UserDefaultDto userDefaultDto) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        String userId = commonUtils.getUserId();
        //查询我的收益基础状态
        List<String> transOperType = new ArrayList<>();
        transOperType.add(TransOperTypeEnum.YUE_1004.getCode());//商户收益(激活奖励)
        transOperType.add(TransOperTypeEnum.YUE_1005.getCode());//直接收益
        transOperType.add(TransOperTypeEnum.YUE_1006.getCode());//下级收益
        transOperType.add(TransOperTypeEnum.YUE_1007.getCode());//采购收益
        transOperType.add(TransOperTypeEnum.YUE_1008.getCode());//提现收益
        transOperType.add(TransOperTypeEnum.YUE_1009.getCode());//办公补贴
        transOperType.add(TransOperTypeEnum.YUE_1010.getCode());//金币兑换
        //本月累计余额
        TUserDefaultInfo thisMonth = userDefaultInfoMapper.queryMoney(userId, userDefaultDto.getBrandId(), transOperType, TransTypeEnum.YUE.getCode(), "3");//查询本月收益
        returnMap.put("thisMonth", thisMonth == null ? BigDecimal.ZERO : thisMonth.getTransAmount());//查询本月收益
        //当前可用余额
        TUserInfo userInfo = userInfoMapper.selectTUserInfoByUserId(userId);
        BigDecimal balance = userInfo.getBalanceSum().subtract(userInfo.getBalanceWithdraw()).subtract(userInfo.getBalanceUse());
        returnMap.put("balance", balance);

        //商户收益//用户名、终端号、日期时间、金额(筛选条件（品牌，日纬度和月维度））
        List<String> type = new ArrayList<>();
        if (userDefaultDto.getTransOperType().equals("0")) {//分润收益//用户名、交易额、日期时间、收益金额(筛选条件(同上））
            type.add(TransOperTypeEnum.YUE_1004.getCode());//商户收益(激活奖励)
        } else if (userDefaultDto.getTransOperType().equals("1")) {
            type.add(TransOperTypeEnum.YUE_1005.getCode());//直接收益
            type.add(TransOperTypeEnum.YUE_1006.getCode());//下级收益
        } else if (userDefaultDto.getTransOperType().equals("2")) {//导师收益//用户名、日期时间、导师奖励金额(筛选条件（同上））
            type.add(TransOperTypeEnum.YUE_1007.getCode());//采购收益
            type.add(TransOperTypeEnum.YUE_1008.getCode());//提现收益
            type.add(TransOperTypeEnum.YUE_1009.getCode());//办公补贴
        }

        List<UserDefaultVo> returnsDetailed = userDefaultInfoMapper.queryDetailList(userId, userDefaultDto.getBrandId(), type, TransTypeEnum.YUE.getCode(), userDefaultDto.getCreateTime());
        Optional.ofNullable(returnsDetailed).ifPresent(list -> {
            returnMap.put("total",new PageInfo(list).getTotal());
            list.stream().forEach(bean -> {
                bean.setGoldTypeShow(Optional.ofNullable(GoodsTypeEnum.getEnumsByCode(bean.getGoldType())).map(item -> item.getValue()).orElse(bean.getGoldType()));
                bean.setTransTypeShow(Optional.ofNullable(TransTypeEnum.getEnumsByCode(bean.getTransType())).map(item -> item.getValue()).orElse(bean.getTransType()));
                bean.setTransOperTypeShow(Optional.ofNullable(TransOperTypeEnum.getEnumsByCode(bean.getTransOperType())).map(item -> item.getValue()).orElse(bean.getTransOperType()));
            });
        });
        returnMap.put("returnsDetailed", returnsDetailed);
        return returnMap;
    }


    @Override
    public UserVipVo queryUserVip() throws Exception {
        String userId = commonUtils.getUserId();
        TUserInfo userInfo = userInfoMapper.selectTUserInfoByUserId(userId);
        TGradeInfo tGradeInfo = tGradeInfoMapper.selectTGradeInfoById(userInfo.getGradeId());
        DataStatisticsDto dto = new DataStatisticsDto();
        dto.setUserId(userId);
        DataStatisticsVo statisticsVo = tStatisticInfoMapper.queryTStatisticSum(dto);
        UserVipVo vipVo = new UserVipVo();
        BeanUtils.copyProperties(userInfo, vipVo);
        BeanUtils.copyProperties(tGradeInfo, vipVo);
        vipVo.setMyTransMoney(statisticsVo.getMyTransMoney() == null ? BigDecimal.ZERO : statisticsVo.getMyTransMoney());//我的交易金额
        vipVo.setMyTerminalNum(statisticsVo.getMyTerminalNum() == null ? BigDecimal.ZERO : statisticsVo.getMyTerminalNum());//我的终端数
        return vipVo;
    }

    /*public static void main(String[] args) {
        BigDecimal c = new BigDecimal(20.00000000);
        BigDecimal v = new BigDecimal(20);
        System.out.println((c == null ? BigDecimal.ZERO : c).compareTo(v) > -1);
        System.out.println("--------------");
    }*/

    @Override
    @Transactional
    public void userWithdrawDeposit(UserDefaultDto dto) throws Exception {
        TRebateSetInfo set = commonService.queryTRebateSetInfoVo();
        if ((set.getBillAmount() == null ? BigDecimal.ZERO : set.getBillAmount()).compareTo(dto.getTransAmount()) > 0) {
            throw new RuntimeException("提现额度不能低于：" + set.getBillAmount());
        }
        String userId = commonUtils.getUserId();
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(userId);
        if ((user.getBalanceSum().subtract(user.getBalanceUse()).subtract(user.getBalanceWithdraw()).compareTo((dto.getTransAmount())) < 0)) {
            throw new RuntimeException("余额不足");
        }
        TUserDefaultInfo defaultInfo = commonUtils.generateTUserDefaultInfo(
                userId,
                "",
                TransTypeEnum.YUE.getCode(),
                TransOperTypeEnum.YUE_1003.getCode(),
                dto.getTransAmount(),
                "",
                "",
                null,
                "",
                null);
        defaultInfo.setCheckStatus(AuditStatusEnum.WAIT_AUDIT.getCode());
        defaultInfo.setServiceChargeAmount((defaultInfo.getTransAmount()).multiply(set.getServiceCharge() == null ? BigDecimal.ZERO : set.getServiceCharge())); //计算手续费
        defaultInfo.setWithdrawAmount(defaultInfo.getTransAmount().subtract(defaultInfo.getServiceChargeAmount()));
        userDefaultInfoMapper.insertTUserDefaultInfo(defaultInfo);
        //更新用户表已提现额度
        user.setBalanceWithdraw(user.getBalanceWithdraw().add(dto.getTransAmount()));
        userInfoMapper.updateTUserInfo(user);
    }


    @Override
    public List<UserDefaultVo> queryUserWithdrawDeposit(UserDefaultDto dto) throws Exception {
        List<UserDefaultVo> listVo = new ArrayList<>();
        String userId = commonUtils.getUserId();
        PageUtil.startPage(dto);
        dto.setUserId(userId);
        dto.setTransType(TransTypeEnum.YUE.getCode());
        dto.setTransOperType(TransOperTypeEnum.YUE_1003.getCode());
        List<TUserDefaultInfo> tUserDefaultInfos = userDefaultInfoMapper.queryUserWithdraw(dto);
        Optional.ofNullable(tUserDefaultInfos).ifPresent(map -> {
            map.stream().forEach(bean -> {
                UserDefaultVo vo = new UserDefaultVo();
                BeanUtils.copyProperties(bean, vo);
                vo.setCheckStatusShow(Optional.ofNullable(AuditStatusEnum.getEnumsByCode(vo.getCheckStatus())).map(item -> item.getShow()).orElse(vo.getCheckStatus()));//提现中午名称
                vo.setGoldTypeShow(Optional.ofNullable(GoodsTypeEnum.getEnumsByCode(vo.getGoldType())).map(item -> item.getValue()).orElse(vo.getGoldType()));
                vo.setTransTypeShow(Optional.ofNullable(TransTypeEnum.getEnumsByCode(vo.getTransType())).map(item -> item.getValue()).orElse(vo.getTransType()));
                vo.setTransOperTypeShow(Optional.ofNullable(TransOperTypeEnum.getEnumsByCode(vo.getTransOperType())).map(item -> item.getValue()).orElse(vo.getTransOperType()));
                listVo.add(vo);
            });
        });
        return listVo;
    }

    @Override
    @Transactional
    public JSONObject userSignContract(UserDto userDto) throws Exception {
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(commonUtils.getUserId());
        JSONObject result = new JSONObject();
        JSONObject jo = new JSONObject();
        if (StringUtils.isEmpty(user.getMemberNo())) { //说明没有趣工宝会员号
            //先调用趣工宝创客注册接口，进行会员注册
            //user.getUserName()用户名称
            //user.getUserPhone()手机号
            //user.getIdentityMark()身份证号
            //user.getBankCardMark()银行卡号
            jo = qugongbaoUtils.memberRegUrl(user.getUserName(), user.getUserPhone(), user.getIdentityMark(), "BANK", user.getBankCardMark());
            log.info("------------------"+"userName:" + user.getUserName() + ",userPhone:" + user.getUserPhone() + ",IdentityMark:" + user.getIdentityMark() + ",bankCardMark" + user.getBankCardMark());
            log.info(jo.toJSONString());
            if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))) {
                List<MemberRegDto> list = JsonUtils.jsonToList(JSONObject.parseObject(jo.get("body").toString()).getString("dataList"), MemberRegDto.class);
                Optional.ofNullable(list).ifPresent(lists ->{
                    lists.stream().forEach(bean ->{
                        if ("0000".equals(bean.getCode())) {
                            user.setMemberNo(bean.getMemberNo());
                            user.setMemberNoTime(DateUtils.getNowDate());

                            System.out.println(bean.getMemberName() + "-------" + bean.getMemberNo());
                        } else {
                            throw new RuntimeException("获取趣工宝会员编号失败，失败信息：" + bean.getMsg());
                        }
                    });
                });
            } else {
                throw new RuntimeException("注册申请失败:" + jo.get("msg"));
            }
        }
        log.info("前端请求的签约地址：" + userDto.getPageCallbackUrl());
        //根据会员编号等四要素，调用趣工宝签约接口，进行趣工宝功能签约
        jo = qugongbaoUtils.queryContractStatus(user.getMemberNo(), null);
        if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))){
            String contractStatus = JSONObject.parseObject(jo.get("body").toString()).getString("contractStatus");
            log.info(user.getUserName() + "签约状态:" + contractStatus);
            if ("2".equals(contractStatus)){
                String contractNo = JSONObject.parseObject(jo.get("body").toString()).getString("contractNo");
                user.setSignStatus(AuditStatusEnum.PASS_AUDIT.getCode());
                user.setContractNo(contractNo);
                userInfoMapper.updateTUserInfo(user);
                result = JSONObject.parseObject(jo.get("body").toString());
                return result;
            } else {
                jo = qugongbaoUtils.signContract(user.getMemberNo(), env.getProperty("qugongbao.signContractResultNotify"), userDto.getPageCallbackUrl());
                user.setSignTime(DateUtils.getNowDate());
                if ("0000".equals(jo.get("code")) && StringUtils.isNotNull(jo.get("body"))) {
                    String contractSignUrl = JSONObject.parseObject(jo.get("body").toString()).getString("contractSignUrl");
                    String contractNo = JSONObject.parseObject(jo.get("body").toString()).getString("contractNo");
                    result = JSONObject.parseObject(jo.get("body").toString());
                    user.setSignStatus(AuditStatusEnum.WAIT_AUDIT.getCode());
                    user.setContractNo(contractNo);
                    user.setContractSignUrl(contractSignUrl);
                    userInfoMapper.updateTUserInfo(user);
                } else { //签约申请失败
                    throw new RuntimeException("签约申请失败：" + jo.get("msg"));
                }
            }
        } else { //签约申请失败
            throw new RuntimeException("查询签约状态失败：" + jo.get("msg"));
        }

        return result;
    }

}
